import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'
import { useUserStore } from '@/store/userStore'

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/v4',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})
// 从 Pinia store 获取当前语言
let languageStore = {}
let currentLang = 'zh-cn'
try {
  const storedLanguage = localStorage.getItem('language')
  if (storedLanguage && typeof storedLanguage === 'string') {
    languageStore = JSON.parse(storedLanguage)
    currentLang = languageStore.currentLang || 'zh-cn'
  }
} catch (error) {
  console.warn('解析语言设置失败，使用默认语言:', error)
  languageStore = {}
  currentLang = 'zh-cn'
}

//获取对应语言
const t = (key) => {
  return (languageStore.langContent && languageStore.langContent[key]) || key
}
// 请求拦截器
service.interceptors.request.use(
  config => {
    // 从 localStorage 获取 token
    const token = localStorage.getItem('user-token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 添加语言头（前后端分离多语言支持）
    try {

      
      // 设置自定义语言头
      config.headers['X-Language'] = currentLang
      
      // 同时设置标准 Accept-Language 头
      const langMap = {
        'zh-cn': 'zh-CN,zh;q=0.9',
        'en-us': 'en-US,en;q=0.9',
        'ja-jp': 'ja-JP,ja;q=0.9',
        'be-by': 'be-BY,be;q=0.9'
      }
      config.headers['Accept-Language'] = langMap[currentLang] || 'zh-CN,zh;q=0.9'
      
    } catch (error) {
      // 如果获取语言失败，使用默认语言
      config.headers['X-Language'] = 'zh-cn'
      config.headers['Accept-Language'] = 'zh-CN,zh;q=0.9'
    }
    
    return config
  },
  error => {
    console.error('请求错误：', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    // 如果返回的状态码不是 200，则判断为错误
    if (response.status !== 200) {
      ElMessage({
        message: t(res.msg) || '请求错误',
        type: 'error',
        duration: 5 * 1000
      })
      
      // 401: 未授权
      if (response.status === 401) {
        // 可以在这里处理登出逻辑
      }
      
      return Promise.reject(new Error(t(res.msg) || '请求错误'))
    } else {
      if(res.code === 401){
        //清空用户记录  并跳转至首页
        localStorage.removeItem('user-token')
        const userStore = useUserStore();
        userStore.logout();
        router.push('/')
      }
      return res
    }
  },
  error => {
    console.error('响应错误：', error)
    ElMessage({
      message: t(error.msg) || '请求失败',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
